package cn.tannn.cat.file.server.util;

import cn.tannn.cat.file.sdk.config.LocalConfig;
import cn.tannn.cat.file.sdk.core.local.LocalDirverUtil;
import cn.tannn.cat.file.server.init.LocalInitDynamicResourceHandlerManager;
import lombok.extern.slf4j.Slf4j;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static cn.tannn.cat.file.server.init.LocalInitDynamicResourceHandlerManager.DEFAULT_NAME;

/**
 * 文件工具
 *
 * @author <a href="https://t.tannn.cn/">tan</a>
 * @version V1.0
 * @date 2025/6/3 15:25
 */
@Slf4j
public class FileUtils {

    public static final String PATH_STR_1 = "/";
    public static final String PATH_STR_2 = "//";

    /**
     * 验证上传目录是否存在
     * @param uploadDir 目录
     * @return true 存在，false 不存在
     */
    public static boolean exist(String uploadDir){
        // 验证目录是否存在
        Path dirPath = Paths.get(uploadDir);
        if (!Files.exists(dirPath)) {
            log.warn("上传目录不存在，跳过配置: {}", uploadDir);
            return false;
        }
        return true;
    }

    /**
     *  追加资源映射
     * @param localConfig  localConfig
     * @param localInitDynamicResourceHandlerManager 动态资源处理器管理器
     */
    public static void appendResourceMapping(LocalConfig localConfig,
                                             LocalInitDynamicResourceHandlerManager localInitDynamicResourceHandlerManager){
        String uploadDir = localConfig.getUploadDir();
        if (!uploadDir.endsWith(PATH_STR_1) && !uploadDir.endsWith(PATH_STR_2)) {
            uploadDir = uploadDir + PATH_STR_1;
        }
        localInitDynamicResourceHandlerManager.appendResourceHandler(
                DEFAULT_NAME,
                LocalDirverUtil.contextPath(localConfig.getContextPath()),
                "file:" + uploadDir
        );
    }


    /**
     *  删除资源映射
     * @param localConfig  localConfig
     * @param localInitDynamicResourceHandlerManager 动态资源处理器管理器
     */
    public static void removeResourceMapping(LocalConfig localConfig,
                                             LocalInitDynamicResourceHandlerManager localInitDynamicResourceHandlerManager){
        String uploadDir = localConfig.getUploadDir();
        if (!uploadDir.endsWith(PATH_STR_1) && !uploadDir.endsWith(PATH_STR_2)) {
            uploadDir = uploadDir + PATH_STR_1;
        }
        localInitDynamicResourceHandlerManager.removeResourceHandler(
                DEFAULT_NAME,
                LocalDirverUtil.contextPath(localConfig.getContextPath()),
                "file:" + uploadDir
        );
    }
}
